package com.wgts.wgts.mvp.view.activity.otherhomepage;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.wgts.wgts.R;
import com.wgts.wgts.base.LazyBaseFragment;
import com.wgts.wgts.control.statusBar.IsplayHelper;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerOtherFragmentComponent;
import com.wgts.wgts.dagger.module.OtherFragmentModule;
import com.wgts.wgts.localbean.LocalAppModleResult;
import com.wgts.wgts.mvp.presenter.IOtherFragmentPresenter;
import com.wgts.wgts.mvp.view.IOtherFragmentView;
import com.wgts.wgts.mvp.view.activity.goodsinfo.JDGoodinfoActivity;
import com.wgts.wgts.mvp.view.activity.homapge.ClassBannerViewHolder;
import com.wgts.wgts.mvp.view.activity.webactivity.WebActivity;
import com.wgts.wgts.netmodle.resp.AppModleEntity;
import com.wgts.wgts.netmodle.resp.ClassBannerEntity;
import com.wgts.wgts.netmodle.resp.GoodProductEntity;
import com.wgts.wgts.tools.Tools;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/*
 *
 *
 *   data:2018/9/1711:41
 *
 */public class OtherFragment extends LazyBaseFragment implements IOtherFragmentView {
    Unbinder unbinder;
    @BindView(R.id.other_recycle)
    RecyclerView otherRecycle;
    @BindView(R.id.shop_class_banner)
    MZBannerView shopClassBanner;
    @BindView(R.id.shop_view_page)
    ViewPager shopViewPage;
    @BindView(R.id.circle_group)
    LinearLayout circleGroup;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;

    //测试分类数据
    private List<LocalAppModleResult> list = new ArrayList<>();
    private OtherRecycleAdapter adapter;
    //测试recycleView数据
    private List<String> products = new ArrayList<>();
    //测试banner数据
    private List<AppModleEntity.AppModleResult> banners = new ArrayList<>();

    private static final String TYPE_ID = "type_id";

    private String typeId;

    private List<Fragment> fragments;


    private ImageView imageView;

    private ImageView[] imageViews;


    private LinearLayoutManager linearLayoutManager;


    @Inject
    IOtherFragmentPresenter presenter;

    List<GoodProductEntity.Entity> searchShopResultEntities;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.other_fragment_change, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void init() {

        searchShopResultEntities = new ArrayList<>();

        typeId = getArguments().getString(TYPE_ID);

        DaggerOtherFragmentComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .otherFragmentModule(new OtherFragmentModule(this))
                .build()
                .inject(this);

    }

    private void initView() {

        smartRefreshLayout.setEnableLoadmore(true);
        smartRefreshLayout.setEnableLoadmore(true);

        linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        otherRecycle.setLayoutManager(linearLayoutManager);
        adapter = new OtherRecycleAdapter(getContext(), searchShopResultEntities);
        otherRecycle.setAdapter(adapter);

        adapter.setOnclickListener(new OtherRecycleAdapter.OnClickListener() {

            @Override
            public void onClick(View view, int i) {
                Intent intent = new Intent(getContext(), JDGoodinfoActivity.class);
                intent.putExtra(JDGoodinfoActivity.JOIN_TYPE, JDGoodinfoActivity.NOMAL);
                intent.putExtra(JDGoodinfoActivity.PRODUCT_ID, String.valueOf(searchShopResultEntities.get(i).productId));
                startActivity(intent);
            }
        });

        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.moreGoodProduct();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.initHead(5, Integer.valueOf(typeId));
                presenter.initGoodProduct(Integer.valueOf(typeId));
                presenter.initBanner(Integer.valueOf(typeId));
            }
        });

    }


    @Override
    protected void loadData() {
        presenter.initHead(5, Integer.valueOf(typeId));
        presenter.initGoodProduct(Integer.valueOf(typeId));
        presenter.initBanner(Integer.valueOf(typeId));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static Fragment getInstanceBundle(String typeId) {
        OtherFragment otherFragment = new OtherFragment();
        Bundle bundle = new Bundle();
        bundle.putString(TYPE_ID, typeId);
        otherFragment.setArguments(bundle);
        return otherFragment;
    }


    private void initSubTypes(List<AppModleEntity.AppModleResult> shopClass) {


        list.clear();
        for (AppModleEntity.AppModleResult result : shopClass) {
            LocalAppModleResult appModleResult = new LocalAppModleResult();
            appModleResult.actionUrl = result.actionUrl;
            appModleResult.id = result.id;
            appModleResult.name = result.name;
            appModleResult.sourceUrl = result.sourceUrl;
            appModleResult.visible = result.visible;
            list.add(appModleResult);
        }
        initShopClass(list);
    }

    @Override
    public void inithead(List<AppModleEntity> appModleEntities) {
        Log.d("", "");


        for (AppModleEntity entity : appModleEntities) {
            if (entity.type.equals("SCROLL_PIC")) {
                //initBanner(entity.result);
            }
            if (entity.type.equals("SUB_TYPES")) {
                //ToDO
                initSubTypes(entity.result);
            }

        }
    }

    @Override
    public void initProductList(GoodProductEntity entity, boolean noMore) {
        smartRefreshLayout.finishRefresh();
        searchShopResultEntities.clear();
        searchShopResultEntities.addAll(entity.list);
        adapter.setNoMore(noMore);
        adapter.notifyDataSetChanged();

        if (noMore) {
            smartRefreshLayout.setEnableLoadmore(false);
        } else {
            smartRefreshLayout.setEnableLoadmore(true);
        }
    }

    @Override
    public void moreProductList(GoodProductEntity entity, boolean noMore) {
        searchShopResultEntities.addAll(entity.list);
        adapter.setNoMore(noMore);
        adapter.notifyDataSetChanged();
        smartRefreshLayout.finishLoadmore();
        if (noMore) {
            smartRefreshLayout.setEnableLoadmore(false);
        } else {
            smartRefreshLayout.setEnableLoadmore(true);
        }
    }

    @Override
    public void initBanner(List<ClassBannerEntity> bannerEntities) {
        initBanner(shopClassBanner, bannerEntities);
    }


    private void initShopClass(List<LocalAppModleResult> shopClassData) {
        List<LocalAppModleResult> groupList = new ArrayList<>();
        List<List<LocalAppModleResult>> showList = new ArrayList<>();
        fragments = new ArrayList<>();
        for (int i = 1; i <= shopClassData.size(); i++) {
            groupList.add(shopClassData.get(i - 1));
            if (i >= 8 && i % 8 == 0) {
                showList.add(groupList);
                groupList = new ArrayList<>();
            }
            if (i >= 8 && i == shopClassData.size() && i % 8 != 0) {
                showList.add(groupList);
            }
            if (i < 8 && i == shopClassData.size()) {
                showList.add(groupList);
            }
        }

        for (int i = 0; i < showList.size(); i++) {
            fragments.add(ShopClassFragment.getShopClassFragment(showList.get(i)));
        }

        if (fragments.size() > 1) {
            initPoint(circleGroup, fragments.size());
            pageChange(shopViewPage);
        }

        shopViewPage.setAdapter(new ShopClassViewPageAdapter(getChildFragmentManager(), fragments));
    }


    //动态加载指示器
    private void initPoint(LinearLayout group, int ViewPageSize) {
        //有多少个界面就new多长的数组
        imageViews = new ImageView[ViewPageSize];
        group.removeAllViews();
        for (int i = 0; i < imageViews.length; i++) {
            //new新的ImageView控件
            imageView = new ImageView(getContext());
            //设置控件的宽高
            imageView.setLayoutParams(new LinearLayout.LayoutParams(IsplayHelper.dpToPx(7), IsplayHelper.dpToPx(7)));
            imageView.setLayoutParams(Tools.setViewMargin(imageView, true, 0, 10, 0, 0));
            imageViews[i] = imageView;
            //初始化第一个page页面的图片的原点为选中状态
            if (i == 0) {
                //表示当前图片
                imageViews[i].setBackgroundResource(R.drawable.select);
                /**
                 * 在java代码中动态生成ImageView的时候
                 * 要设置其BackgroundResource属性才有效
                 * 设置ImageResource属性无效
                 */
            } else {
                imageViews[i].setBackgroundResource(R.drawable.unselect);
            }
            //把new出来的ImageView控件添加到线性布局中
            group.addView(imageViews[i]);
        }
    }

    private void initBanner(MZBannerView mzBannerView, final List<ClassBannerEntity> banners) {
//        mzBannerView.setPages(banners, new MZHolderCreator() {
//            @Override
//            public MZViewHolder createViewHolder() {
//                return new BannerViewHolder();
//            }
//        });
//        mzBannerView.start();


        DisplayMetrics outMetrics = Tools.metrics(getActivity());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(outMetrics.widthPixels, (int) (outMetrics.widthPixels * 0.45));
        mzBannerView.setLayoutParams(layoutParams);
        Tools.setViewMargin(mzBannerView, true, 0, 0, 44, 10);

        mzBannerView.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {

                Intent intent = null;

                if (banners.get(i).linkType.equals("0")) {
                    intent = new Intent(getActivity(), WebActivity.class);
                    intent.putExtra(WebActivity.ACTION_URL, banners.get(i).link);
                } else {
                    intent = new Intent(getActivity(), JDGoodinfoActivity.class);
                    intent.putExtra(JDGoodinfoActivity.PRODUCT_ID, banners.get(i).link);
                    intent.putExtra(JDGoodinfoActivity.JOIN_TYPE, JDGoodinfoActivity.NOMAL);
                }
                if (intent != null) {
                    startActivity(intent);
                }
            }
        });

        mzBannerView.setPages(banners, new MZHolderCreator() {
            @Override
            public MZViewHolder createViewHolder() {
                return new ClassBannerViewHolder();
            }
        });
        mzBannerView.start();

    }

    //viewpage滑动状态
    private void pageChange(ViewPager viewPager) {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                //判断当前是在那个page，就把对应下标的ImageView原点设置为选中状态的图片
                for (int i1 = 0; i1 < imageViews.length; i1++) {
                    imageViews[i].setBackgroundResource(R.drawable.select);
                    if (i != i1) {
                        imageViews[i1].setBackgroundResource(R.drawable.unselect);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }


    @Override
    public void onError(int status, String msg) {
        if(smartRefreshLayout != null){
            smartRefreshLayout.finishRefresh();
        }
        MoHuToast.showToast(msg);
    }
}
